/**
 * 
 */
package com.ssc.manager.demo.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ssc.manager.demo.entity.db.UserEntity;
import com.ssc.manager.demo.service.IUserService;

/**
 * 
 * @author duanhx
 * @version [Ver 1.0; 2012-7-22]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@RequestMapping("/demo")
public class UserController {

	@Autowired
	private IUserService userService;
	
	/**
	 * 返回JSON数据体
	 * 
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping("/json")
	@ResponseBody
	public List<UserEntity> userJson(@ModelAttribute UserEntity user) {

		return userService.getUserList(user);
	}
	
	@RequestMapping("/test2")
	@ResponseBody
	public String userTest() {
		return "";
	}
	
	/**
	 * 跳转和查询user时调用此方法
	 * URL: http://host:port/SportsMgt/demo
	 * 
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping("")
	public String user(Model model, @ModelAttribute UserEntity user) {
		List<UserEntity> list = userService.getUserList(user);
		model.addAttribute("userList", list);
		
		return "demo/user";
	}
	
	/**
	 * 删除user
	 * 
	 * @param id
	 * @param redirectAttributes
	 * @return redirect:表示启用重定向跳转, 避免重复提交
	 */
	@RequestMapping(value={"/delete/{id}", "/remove/{id}"})
	public String delete(@PathVariable String id, RedirectAttributes redirectAttributes) {
		userService.deleteUser(new String[]{id});
		redirectAttributes.addFlashAttribute("msg", "删除成功!");
		
		return "redirect:/demo";
	}
	
	/**
	 * 跳转新增修改页面时调用此方法
	 * URL: http://host:port/SportsMgt/demo
	 * 
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/input")
	public String input(@RequestParam(value="id", required=false) Integer id, Model model) {
		UserEntity resultUserEntity = new UserEntity();
		if (id != null) {
			resultUserEntity = userService.getUser(new UserEntity(id));
		} 
		model.addAttribute("user", resultUserEntity);
		
		return "demo/user-input";
	}
	
	/**
	 * 新增或修改user
	 * 
	 * @param user
	 * @param redirectAttributes
	 * @return redirect:表示启用重定向跳转, 避免重复提交
	 */
	@RequestMapping("/save")
	public String save(@ModelAttribute("user") UserEntity user, RedirectAttributes redirectAttributes) {
		userService.saveUser(user);
		redirectAttributes.addFlashAttribute("msg", "保存成功!");
		
		return "redirect:/demo";
	}
}
